import re
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken, AccessToken
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from .serializers import UserInfoSerializer, UserUpdateSerializer
from .models import User
# Create your views here.
# 注册接口
class RegisterView(APIView):
    permission_classes = [] # 无需权限限制
    def post(self, request):
        # 接收参数
        username = request.data.get('username')
        password = request.data.get('password')
        # 校验参数
        if not all([username, password]):
            return Response({'success': False, 'message': '用户名和密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        # 用户名正则：4到16位，只能包含字母、数字、下划线、减号（注意减号不能出现在首位）
        if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', username):
            return Response({'success': False, 'message': '用户名格式错误'}, status=status.HTTP_400_BAD_REQUEST)
        # 密码正则：8到16位，包括至少一位大写字母，一位小写字母，一个数字，一个特殊字符
        if not re.match(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$', password):
            return Response({'success': False, 'message': '密码格式错误'}, status=status.HTTP_400_BAD_REQUEST)
        # 检查用户是否存在
        if User.objects.filter(username=username).exists():
            return Response({'success': False, 'message': '用户名已存在'}, status=status.HTTP_400_BAD_REQUEST)
        # 创建用户
        try:
            user = User.objects.create_user(username=username, password=password)
            user.save()
            # 返回响应
            return Response({'success': True, 'message': '注册成功'}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'success': False, 'message': '注册失败'}, status=status.HTTP_400_BAD_REQUEST)

# 获取用户信息接口
class UserInfoView(APIView):
    permission_classes = [IsAuthenticated] # 需要登录
    def get(self, request):
        user = request.user
        serializer = UserInfoSerializer(user)
        return Response({
            "success": True,
            "message": "获取用户信息成功",
            "data": serializer.data
        }, status=status.HTTP_200_OK)

# 更新用户信息接口
class UserUpdateView(APIView):
    permission_classes = [IsAuthenticated] # 需要登录
    def put(self, request):
        user = request.user
        serializer = UserUpdateSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True, 
                'message': '更新成功'
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False, 
                'message': '更新失败',
                'errors': serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)

class TestView(APIView):
    def post(self, request, *args, **kwargs):
        s = str(request.user.__dict__)
        return Response({'success': True, 'message': s}, status=status.HTTP_200_OK)